package com.yindian.cos.easy.security.authentication.login.social.weibo;

import com.alibaba.fastjson.JSONObject;
import com.yindian.cos.easy.security.authentication.login.social.core.AbstractAccessTokenFactory;
import com.yindian.cos.easy.security.authentication.login.social.core.AccessToken;
import com.yindian.cos.easy.security.constant.ProviderName;
import com.yindian.cos.easy.security.exception.AccessTokenException;
import com.yindian.cos.easy.security.properties.EasySecurityProperties;
import com.yindian.cos.easy.security.properties.WeiBoProperties;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 微博获取access_token默认实现
 *
 * @author zhangchuanhao
 * @create 2018/11/20
 */
public class WeiBoAccessTokenFactory extends AbstractAccessTokenFactory {

    private final EasySecurityProperties easySecurityProperties;

    private final RestTemplate restTemplate;

    public WeiBoAccessTokenFactory(EasySecurityProperties easySecurityProperties, RestTemplate restTemplate) {
        this.easySecurityProperties = easySecurityProperties;
        this.restTemplate = restTemplate;
    }

    @Override
    public AccessToken getAccessToken(String code) {
        try {
            WeiBoProperties weiBoProperties = easySecurityProperties.getWeibo();
            String url = weiBoProperties.getAccessTokenUrl();
            String redirectUrl = weiBoProperties.getDomain() + weiBoProperties.getRedirectUri().trim();

            MultiValueMap<String, String> params = new LinkedMultiValueMap();
            params.add("grant_type", weiBoProperties.getGrantType());
            params.add("client_id", weiBoProperties.getAppKey());
            params.add("client_secret", weiBoProperties.getAppSecret());
            params.add("code", code);
            params.add("redirect_uri", redirectUrl);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity(params, headers);

            String result = restTemplate.postForEntity(url, requestEntity, String.class).getBody();
            WeiBoAccessToken weiBoAccessToken = JSONObject.parseObject(result, WeiBoAccessToken.class);
            Map<String, Object> map = new HashMap<>(1);
            map.put("weiBoAccessToken", weiBoAccessToken);
            AccessToken accessToken = new AccessToken(weiBoAccessToken.getAccess_token(), weiBoAccessToken.getUid(), map);
            return accessToken;
        } catch (Exception e) {
            throw new AccessTokenException(ProviderName.WEIBO + "登录获取access_token失败", e.getCause());
        }
    }
}
